#!/bin/bash

# This script is to be run on AlluxioMaster to RSYNC a file/directory to all AlluxioWorkers
# e.x. run `/vagrant-utils/copy-dir /alluxio/conf` on master will RSYNC alluxio conf to all workers
# this is helpful when you change configurations on master and then RSYNC to all workers

# Modified from https://github.com/mesos/spark-ec2/blob/branch-1.4/copy-dir.sh

DELETE_FLAG=""

usage() {
 echo "Usage: copy-dir [--delete] <dir>"
 exit 1
}

while :
do
 case $1 in
  --delete)
   DELETE_FLAG="--delete"
   shift
   ;;
  -*)
   echo "ERROR: Unknown option: $1" >&2
   usage
   ;;
  *) # End of options
   break
   ;;
 esac
done

if [[ "$#" != "1" ]]; then
 usage
fi

if [[ ! -e "$1" ]]; then
 echo "File or directory $1 doesn't exist!"
 exit 1
fi

DIR=`readlink -f "$1"`
DIR=`echo "$DIR"|sed 's@/$@@'`
DEST=`dirname "$DIR"`

WORKERS=`head -n -1 /vagrant/files/workers`

SSH_OPTS="-o StrictHostKeyChecking=no -o ConnectTimeout=5"

echo "RSYNC'ing $DIR to workers..."
for worker in $WORKERS; do
    echo $worker
    rsync -e "ssh $SSH_OPTS" -az $DELETE_FLAG "$DIR" "$worker:$DEST" & sleep 0.5
done
wait
